package com.wzh.user.service.impl;

import com.wzh.common.utils.JwtUtil;
import com.wzh.common.utils.R;
import com.wzh.user.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.user.dao.UserDao;
import com.wzh.user.entity.UserEntity;
import com.wzh.user.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Value("${register.salt}")
    private String salt;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserEntity user) {
        user.setPassword(Md5Util.md5salt(Md5Util.md5salt(user.getPassword(),salt),salt));
        user.setSalt(salt);
        user.setRegisterDate(new Date());
        baseMapper.insert(user);
    }

    @Override
    public R login(String nickname, String password) {
        UserEntity user = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("nickname", nickname));
        if (user!=null){
            if (user.getPassword().equals(Md5Util.md5salt(Md5Util.md5salt(password,salt),salt))){
                String token = jwtUtil.createJWT(user.getId().toString(), user.getNickname(), "admin");
                UserEntity userEntity=user;
                userEntity.setLoginCount(userEntity.getLoginCount()+1);
                userEntity.setLastLoginDate(user.getNowDate());
                userEntity.setNowDate(new Date());
                baseMapper.updateById(userEntity);
                return R.ok("登陆成功").put("token",token);
            }
            return R.error("用户名或密码错误");
        }
        return R.error("用户名或密码错误");
    }
}